package net.example.activity;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import net.example.activity.adapter.UserBasicAdapter;
import net.example.manager.ClientGlobalCache;
import net.example.manager.Manager;
import net.example.model.BasicResult;
import net.example.model.CreateGroupResult;
import net.example.model.Group_Friend_SelectorType;
import net.example.model.GroupType;
import net.example.model.GGGroup;
import net.example.model.GGUser;
import net.example.model.UserBasicModel;
import net.example.ggtalk.R;
import com.oraycn.esbasic.helpers.StringHelper;
import com.oraycn.esbasic.objectManagement.cache.HotCache;

import net.example.utils.CommonHelper;
import net.example.utils.ToastUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;
//讨论组，好友选择器
public class Group_Friend_SelectorActivity extends Activity implements View.OnClickListener, AdapterView.OnItemClickListener {

    private UserBasicAdapter adapter;
    private List<UserBasicModel> modelList =new ArrayList<UserBasicModel>();
    private int selectedCount=0;//选中的数量
    private TextView tv_userCount;
    private CheckBox checkBox;
    private boolean isRequesting=false;//正在请求服务端  （以免多次点击按钮，造成多次创建）
    private Group_Friend_SelectorType type;//组中成员变动类型
    private GGGroup group;//新增时为空，修改时传入值
    private List<String> groupMemberList=new ArrayList<>();//组中修改前的成员集合

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_group);
        type=(Group_Friend_SelectorType)getIntent().getSerializableExtra("groupFriendSelectorType");
        String groupID=getIntent().getStringExtra("groupID");
        if(!StringHelper.isNullOrEmpty(groupID))
        {
            group=ClientGlobalCache.getInstance().getGroup(groupID);
        }
        this.initView();
        this.initListView();
    }

    private void initView()
    {
        this.tv_userCount=(TextView)findViewById(R.id.tv_userCount);
        this.checkBox=(CheckBox)findViewById(R.id.checkBox);
        Button button=(Button) findViewById(R.id.btn_confirm);
        button.setText("确认");
        button.setVisibility(View.VISIBLE);
        button.setOnClickListener(this);
        TextView title=(TextView)findViewById(R.id.headerText);
        switch (type)
        {
            case AddMember4CreateGroup:
                title.setText("创建群组");
                this.checkBox.setVisibility(View.VISIBLE);
                break;
            case PullMemberInGroup:
                title.setText("请选择");
                break;
            case TickMemberOutGroup:
                title.setText("请选择");
                break;
            case ShareMessage:
                title.setText("请选择");
                button.setText("发送");
                break;
            case AtMemberInGroup:
                title.setText("选择提醒的人");
                break;
            case VideoChatMemberInGroup:
                title.setText("选择群视频成员");
                break;
        }

    }


    private void initListView()
    {
        List<String> userIDList=null;
        if(group!=null)
        {
            groupMemberList= group.getChildMemberList();
        }
        switch (type)
        {
            case AddMember4CreateGroup:
                userIDList=ClientGlobalCache.getInstance().getCurrentUser().getFriendList();
                break;
            case PullMemberInGroup:
                userIDList=ClientGlobalCache.getInstance().getCurrentUser().getFriendList();
                userIDList.removeAll(groupMemberList);//差集
                break;
            case TickMemberOutGroup:
                groupMemberList.remove(ClientGlobalCache.getInstance().getCurrentUser().getUserID());//列表移除自己
                userIDList=groupMemberList;
                break;
            case ShareMessage:
                userIDList=ClientGlobalCache.getInstance().getCurrentUser().getFriendList();
                String talkingID= getIntent().getStringExtra("talkingID");
                //群转发对象排除当前正在聊天的
                userIDList.remove(talkingID);
                Collection<GGGroup> groups=ClientGlobalCache.getInstance().getGroups();
                for (GGGroup group:groups)
                {
                    if(group.getGroupID().equals(talkingID))
                    {
                        groups.remove(group);
                        break;
                    }
                }
                this.modelList.addAll(CommonHelper.ggGroupListConvertToUserBasicModel(groups));
                break;
            case AtMemberInGroup:
                userIDList=groupMemberList;
                break;
            case VideoChatMemberInGroup:
                groupMemberList.remove(ClientGlobalCache.getInstance().getCurrentUser().getUserID());
                userIDList=groupMemberList;
                break;
        }
        List<GGUser> userList = ClientGlobalCache.getInstance().getGGUserList(userIDList);
        this.modelList.addAll(CommonHelper.ggUserListConvertToUserBasicModel(userList));
        this.increaseMoreModel();
        ListView listView=(ListView)findViewById(R.id.userList_listView);
        adapter=new UserBasicAdapter(this.modelList,this);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
    }

    //补充额外的Model
    private void increaseMoreModel()
    {
        switch (type)
        {
            case AtMemberInGroup:
                if(group.getCreatorID().equals(ClientGlobalCache.getInstance().getCurrentUser().getUserID()))
                {
                    UserBasicModel allMemberModel= new UserBasicModel("@all","全体成员",-1);
                    this.modelList.add(0,allMemberModel);
                }
                break;
        }

    }




    public void finish(View view)
    {
        finish();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_confirm:
                if(isRequesting)
                {
                    return;
                }
                isRequesting=true;
                if (this.selectedCount == 0) {
                    ToastUtils.showLong(Group_Friend_SelectorActivity.this, "请选择联系人");
                    return;
                }
                switch (type)
                {
                    case AddMember4CreateGroup:
                        this.createGroup();
                        break;
                    case PullMemberInGroup:
                        this.pullMemberInGroup();
                        break;
                    case TickMemberOutGroup:
                        this.tickMemberOutGroup();
                        break;
                    case ShareMessage:
                        this.sendShareMessage();
                        break;
                    case AtMemberInGroup:
                        this.selectMembers4At();
                        break;
                    case VideoChatMemberInGroup:
                        this.selectMember4VideoChat();
                        break;
                }
                isRequesting=false;

                break;
        }
    }

    private void createGroup() {
        Random random = new Random();
        String groupID = "";
        int num = 0;
        do {
            num = Math.abs(random.nextInt()) % 100000;
            groupID = "*" + ClientGlobalCache.getInstance().getCurrentUser().getUserID() + "_" + num;
        } while (ClientGlobalCache.getInstance().isGroupExist(groupID));
        String groupName = "未命名" + num;
        List<String> userIDs = this.getUserID4Checked();
        userIDs.add(0, ClientGlobalCache.getInstance().getCurrentUser().getUserID());
        CreateGroupResult createGroupResult = Manager.getInstance().CreateGroup(GroupType.CommonGroup, groupID, groupName, "", userIDs,this.checkBox.isChecked());
        if (createGroupResult == CreateGroupResult.GroupExisted) {
            ToastUtils.showLong(Group_Friend_SelectorActivity.this, "讨论组已存在");
            return;
        } else if (createGroupResult == CreateGroupResult.Error) {
            ToastUtils.showLong(Group_Friend_SelectorActivity.this, "内部错误！");
            return;
        } else {
            ToastUtils.showLong(Group_Friend_SelectorActivity.this, "创建成功！");
            finish();
        }
    }

    private void pullMemberInGroup() {
        List<String> userIDs = this.getUserID4Checked();
        userIDs.removeAll(this.groupMemberList);//去重
        userIDs.addAll(this.groupMemberList);//并集
        BasicResult result = Manager.getInstance().ChangeGroupMembers(group.getGroupID(), userIDs);
        this.showResult(result);
    }

    private void tickMemberOutGroup() {
        List<String> userIDs = this.getUserID4Checked();
        groupMemberList.add(0,ClientGlobalCache.getInstance().getCurrentUser().getUserID());//加上自己
        groupMemberList.removeAll(userIDs);//差集
        BasicResult result = Manager.getInstance().ChangeGroupMembers(group.getGroupID(), groupMemberList);
        this.showResult(result);
    }

    private void sendShareMessage()
    {
        List<String> models= getUserID4Checked();
        HotCache.add("UserBasicModels",models);//传入热缓存中，跳转后获取使用再清除
        setResult(RESULT_OK);
        finish();
    }

    private void selectMembers4At()
    {
        Collection<UserBasicModel> members= getModels4Checked();
        HotCache.add("memberSelected4At",members);//传入热缓存中，跳转后获取使用再清除
        setResult(RESULT_OK);
        finish();
    }

    private void selectMember4VideoChat()
    {
        List<String> models= getUserID4Checked();
        HotCache.add("memberSelected4VideoChat",models);//传入热缓存中，跳转后获取使用再清除
        setResult(RESULT_OK);
        finish();
    }

    private void showResult(BasicResult result) {
        switch (result) {
            case Succeed:
                ToastUtils.showLong(Group_Friend_SelectorActivity.this, "保存成功！");
                finish();
                break;
            case NotExisted:
                ToastUtils.showLong(Group_Friend_SelectorActivity.this, "讨论组不存在！");
                break;
            case Error:
                ToastUtils.showLong(Group_Friend_SelectorActivity.this, "内部错误！");
                break;
        }
    }


    private List<String> getUserID4Checked()
    {
        List<String> userIDs=new ArrayList<String>();
        for (UserBasicModel model:this.modelList) {
            if(model.getChecked())
            {
                userIDs.add(model.getUserID());
            }
        }
        return userIDs;
    }

    private Collection<UserBasicModel> getModels4Checked()
    {
        Collection<UserBasicModel> models=new ArrayList<>();
        for (UserBasicModel model:this.modelList) {
            if(model.getChecked())
            {
                models.add(model);
            }
        }
        return models;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
//        ToastUtils.showLong(AddGroupActivity.this,"view:"+view.getId()+"  position:"+position);
        boolean checked = this.modelList.get(position).changeChecked();
        if (checked) {
            selectedCount++;
        } else {
            selectedCount--;
        }
        tv_userCount.setText(String.format("已选择（%d人）", selectedCount));
        adapter.notifyDataSetChanged();
    }
}
